package com.daidai.activitys

import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.widget.EditText
import android.widget.ProgressBar
import com.daidai.base.BaseActivity
import com.daidai.tools.G
import com.daidai.spinner.R
import com.daidai.tools.ImTool

class BrowserActivity : BaseActivity() {

    lateinit var webView:WebView
    lateinit var etText:EditText
    lateinit var pbBar:ProgressBar

    override fun getContentViewResId() = R.layout.activity_browser

    override fun initView() {
        webView = findViewById(R.id.webView)
        etText = findViewById(R.id.etText)
        pbBar = findViewById(R.id.pbBar)

        val settings = webView.settings
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true//js和android交互
        settings.allowFileAccess = true // 允许访问文件
        settings.setAppCacheEnabled(true) //设置H5的缓存打开,默认关闭
        settings.useWideViewPort = true//设置webview自适应屏幕大小
        // settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.loadWithOverviewMode = true//设置webview自适应屏幕大小
        settings.domStorageEnabled = true//设置可以使用localStorage
        settings.setSupportZoom(false)//关闭zoom按钮
        settings.builtInZoomControls = false//关闭zoom
    }

    override fun initData() {
        webView.loadUrl("https://www.baidu.com")

        etText.setOnEditorActionListener { _, _, p2 ->
            if(p2?.keyCode == KeyEvent.KEYCODE_ENTER){
                var url = etText.text.toString()
                if(!url.startsWith("http")&&!url.startsWith("https")){
                    url="http://$url"
                }
                webView.loadUrl(url)
                ImTool.closeKeyBoard(baseContext,etText)
            }
            false
        }
        webView.webChromeClient = object : WebChromeClient() {

            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if(newProgress >= 99){
                    pbBar.visibility = View.GONE
                }else if(pbBar.visibility == View.GONE){
                    pbBar.visibility = View.VISIBLE
                }
                pbBar.progress = newProgress
            }
        }
        webView.webViewClient = object:WebViewClient(){


            override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
                // super.onReceivedSslError(view, handler, error)
                handler?.proceed()
            }

            // 当页面加载完成后会调用该方法
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                etText.setText(url)
            }

//            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
//                G.elog("====AAA===  shouldOverrideUrlLoading called! url:${request?.url}")
//                super.shouldOverrideUrlLoading(view, request)
//                return true
//            }

            /**
             * 翻译：当一个新的url要在当前WebView进行加载的时候，
             * 这个方法给应用一个机会来控制url的处理。如果WebView没有setWebViewClient，
             * 则默认操作是WebView将询问Activity Manager获取合适的handler处理url。
             * 如果WebView设置了setWebViewClient，返回true代表当前应用来处理url，
             * 返回false则代表当前webview来处理url。如果http请求是POST方法，该方法将不会被调用。
             */
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                // return super.shouldOverrideUrlLoading(view, url)
                G.elog("====BBB===  shouldOverrideUrlLoading called! url:$url")
                view?.loadUrl(url!!)
                return true
            }
        }
        webView.setDownloadListener { url, _, _, _, _ ->
            val i = Intent(Intent.ACTION_VIEW)
            i.data = Uri.parse(url)
            startActivity(i)
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        G.elog("onKeyDown called!")
        if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
            webView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onBackPressed() {
        G.elog("onBackPressed called!")
        if (webView.canGoBack()){
            webView.goBack()
        }else{
            finish()
        }
    }
}